<template>
    <!-- 数据中心/数据源/数据源详情 -->
    <div class="dataDetails">
        <div class="top_operation">
            <div class="every_operation" v-if="isRegionShow">
                <span>大区：</span>
                <a-select
                    show-search
                    :filter-option="filterOption"
                    style="width: 195px" 
                    @change="regionChange" 
                    v-model="regionId" 
                >
                    <a-select-option :key="index" v-for="(item, index) in regionList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation" v-if="isCityShow">
                <span>城市：</span>
                <a-select 
                    show-search
                    :filter-option="filterOption"
                    style="width: 195px" 
                    @change="cityChange" 
                    v-model="cityId"
                >
                    <a-select-option :key="index" v-for="(item, index) in cityList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation" v-if="isWareShow">
                <span>仓库：</span>
                <a-select
                    show-search
                    :filter-option="filterOption" 
                    style="width: 195px" 
                    @change="warehouseChange" 
                    v-model="organizeId"
                >
                    <a-select-option :key="index" v-for="(item, index) in warehouseList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            
            <div class="every_operation">
                <span>开始时间：</span>
                <a-date-picker
                    v-model="createTime_begin"
                    :show-time="showTimeBegin"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择时间" 
                    @change="startChange" 
                    @ok="startOk"
                    :allowClear="allowClear"
                />
            </div>
            <div class="every_operation">
                <span>结束时间：</span>
                <a-date-picker
                    v-model="createTime_end"
                    :show-time="showTimeEnd"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择时间" 
                    @change="endChange" 
                    @ok="endOk"
                    :allowClear="allowClear"
                />
            </div>
            <div class="button_div">
                <a-button type="primary" icon="search" @click="onSearch">搜索</a-button>
                <a-button type="primary" icon="sync" style="margin-left:20px;" @click="onReset">重置</a-button>
                <a-button type="primary" icon="rollback" style="margin-left:20px;" @click="onBack">返回</a-button>
                <!-- <a-button type="primary" style="margin-left:20px;" @click="doExport()" >导入</a-button> -->
                <a-upload v-if="allowImport"
                        accept=".xls,.xlsx"
                        name="file"
                        :beforeUpload="beforeUpload"
                        :data="uploadData"
                        :showUploadList="false"
                        :multiple="false"
                        :action="uploadUrl"
                        :headers="tokenHeader"
                        @change="uploadChange"
                    >
                        <a-button type="primary" style="margin-left:20px;"> 导入 </a-button>
                </a-upload>
                <a-button v-if="allowImport" style="margin-left:20px;" @click="downLoadTemp()">下载模板</a-button>
            </div>
        </div>
        <div class="data_source_list">
            <h3>{{dsName}}</h3>
            <div class="data_source_details">
                <a-table
                    :loading="tableLoading"
                    :columns="columns" 
                    :data-source="data"
                    :pagination="false"
                    bordered
                    rowKey="id"
                    :scroll="xScroll"
                >
                </a-table>
                <!-- 底部分页组件 -->
                <BottomPagination
                    :total="total"
                    @pageChange="pageChange"
                    @sizeChange="sizeChange"
                ></BottomPagination>
            </div>
        </div>
        <!-- 统一导入结果弹窗 -->
        <ImportResultVue
            ref="ImportResultRef"
            @close="isResultModal = false"
            @pageChange="resultPageChange"
            @pageNoChange="pageNoChange"
            :current.sync="current"
            :width="1200"
            title="导入完成"
            :result-total="resultTotal"
            :isResultModal.sync="isResultModal" 
            :columns="columns" 
            :data-source="twoResultData" />
    </div>
</template>

<script>

    import moment from 'moment'
    import TopSelect from '../meter/TopSelect'
    import BottomPagination from '../meter/BottomPagination'
    import ImportResultVue from '@/components/modal/ImportResult.vue'
    import importFileMixin from '../../mixins/importFileMixin.js'
    import { downFile } from '@/api/manage'
    import { downLoadTemp } from '@/utils/util.js'
    import { getHeadquarters, getRegion, getCity, getWarehouse, getDSDetails,getDSDetailsTemp } from '@/api/api'
    export default {
        inject: [ 'reload' ],
        name: "DataDetails",
        mixins:[importFileMixin],
        components: {
            TopSelect,
            BottomPagination,
            ImportResultVue
        },
        data () {
            return {
                columns: [],
                data: [],
                tableLoading: false,
                xScroll: {
                    x: true,
                },
                headquartersId: '', // 总部id
                regionId: '', // 大区id
                cityId: '', // 城市id
                organizeId: '', // 仓库id
                regionList: [],
                cityList: [],
                warehouseList: [],
                isRegionShow: true,
                isCityShow: true,
                isWareShow: true,
                categoryName: '',
                dataName: '',
                dataCode: '',
                dsName: '',
                dsCode: '',
                grade: 0,
                roleGrade: 0, // 当前角色等级
                code: '',
                headquartersCode: '',
                createTime_begin: '',
                createTime_end: '',
                showTimeBegin: {
                    defaultValue: moment("00:00:00", "HH:mm:ss")
                },
                showTimeEnd: {
                    defaultValue: moment("23:59:59", "HH:mm:ss")
                },
                allowClear: false,
                total: 0,
                pageNo: 1,
                pageSize: 10,
                // 权限
                isAuth:'no',
                // 导入
                url: {
                    uploadUrl: '/ds/conf/importExcel',
                    importTemp:'/ds/conf/excel/temp'
                },
            }
        },
        beforeRouteEnter(to, from, next) {
            next(vm=>{
                // 判断是否是从数据源页面跳转过来
                if(from.path == '/datacenter/datasource'){
                    vm.setDataSource()
                }
            })
        },
        created() {
            var dataSource = JSON.parse(sessionStorage.getItem('DATA_SOURCE'))
            this.categoryName = dataSource.categoryName
            this.dataName = dataSource.dataName
            this.dataCode = dataSource.dataCode
            this.dsName = dataSource.dsName
            this.dsCode = dataSource.dsCode
            this.isAuth = dataSource.allowImport

            // 数据源详情默认取今天的数据
            var d = new Date()
            var curDateTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
            this.createTime_begin = curDateTime + ' ' + '00:00:00'
            this.createTime_end = curDateTime + ' ' + '23:59:59'
            this.getHeadquartersList()
        },
        computed:{
            allowImport(){
                return this.isAuth =='yes'
            }
        },
        methods: {
            moment,
            // 选择框过滤
            filterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },

            setDataSource() {
                var dataSource = JSON.parse(sessionStorage.getItem('DATA_SOURCE'))
                this.categoryName = dataSource.categoryName
                this.dataName = dataSource.dataName
                this.dataCode = dataSource.dataCode
                this.dsName = dataSource.dsName
                this.dsCode = dataSource.dsCode
                this.isAuth = dataSource.allowImport
                this.data = []
                this.columns = []
                this.total = 0
                this.pageNo = 1
                this.pageSize = 10

                var d = new Date()
                var curDateTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
                this.createTime_begin = curDateTime + ' ' + '00:00:00'
                this.createTime_end = curDateTime + ' ' + '23:59:59'
                this.getHeadquartersList()

                this.$forceUpdate()
            },

            // 上传钩子函数
            beforeUpload(file,fileInfo){
                // if(this.columns.length==0){
                //     this.$message.warning('请先搜索,获取表头！')
                //     return false
                // }
                if( (this.regionId == '' || this.regionId == undefined) || (this.cityId == '' || this.cityId == undefined) || (this.organizeId == '' || this.organizeId == undefined) ){
                    this.$message.warning('导入时必须先选择大区、城市和仓库！')
                    return false
                }
                let isExcal = file.name.split('.')[1]
                if(isExcal=='xls'||isExcal=='xlsx'){
                    Object.defineProperty(this.uploadData,'dsCode',{
                        configurable:true,
                        enumerable:true,
                        writable:true,
                        value:this.dsCode
                    })
                    Object.defineProperty(this.uploadData,'whCode',{
                        configurable:true,
                        enumerable:true,
                        writable:true,
                        value:this.code
                    })
                    return true
                }else{
                    this.$message.error(`导入表格仅支持xls、xlsx格式！`, 6);
                    return false
                }
            },
            // 导入
            uploadChange(info) {
                if (info.file.status !== 'uploading') {
                    console.log(info.file);
                }
                if (info.file.status === 'done') {
                    if (info.file.response.success) {
                        this.$message.success(`${info.file.name}文件上传成功！`);
                    } else {
                        this.$message.error(`${info.file.response.message}`)
                        return
                        this.$message.error(`${info.file.name}文件上传失败！`, 6);
                        // this.isResultModal = true
                        if (Array.isArray(info.file.response.result)) {
                            this.resultData = info.file.response.result
                            // this.resultData.forEach(item => {
                            //     item['id'] = Date.now() + Math.random().toString()
                            //     item['customerCode'] = this.customerCode2
                            // })
                            console.log(this.resultData, 'this.resultData')
                            if (info.file.response.result.length) {
                                this.resultTotal = info.file.response.result.length
                            } else {
                                this.resultTotal = 0
                            }
                            if (info.file.response.result.length < 10) {
                                this.twoResultData = info.file.response.result
                            } else {
                                this.twoResultData = info.file.response.result.slice(0, 10)
                            }
                        }
                    }
                } else if (info.file.status === 'error') {
                    this.$message.error(`${info.file.name}文件上传失败！`, 6);
                }
            },
            // 下载模板
            async downLoadTemp(){
                downLoadTemp(await downFile(`${this.url.importTemp}?dsCode=${this.dsCode}`),this.dsName+'导入模板')
            },
            // 获取总部
            getHeadquartersList(){
                let params = {}
                getHeadquarters(params).then((res)=>{
                    if(res.success){
                        this.headquartersId = res.result.organizeOrgList[0].id
                        this.grade = res.result.grade
                        this.roleGrade = res.result.grade
                        this.code = res.result.organizeOrgList[0].code
                        this.headquartersCode = res.result.organizeOrgList[0].code
                        this.getRegionList()
                    }
                })
            },
            // 获取大区
            getRegionList(){
                let params = {id: this.headquartersId}
                getRegion(params).then((res)=>{
                    if(res.success){
                        this.regionList = res.result.organizeOrgList
                        if(this.regionList.length == 1){
                            this.regionId = this.regionList[0].id
                            this.grade = 1
                            this.code = this.regionList[0].code
                            this.getCityList()
                        }
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 选择大区
            regionChange(value){
                this.regionId = value
                this.grade = 1
                for(var item of this.regionList){
                    if(item.id == this.regionId){
                        this.code = item.code
                    }
                }
                this.cityId = ''
                this.organizeId = ''
                this.cityList = []
                this.warehouseList = []
                this.getCityList()
            },
            // 获取城市
            getCityList(){
                let params = {
                    areaIds: this.regionId
                }
                getCity(params).then((res)=>{
                    if(res.success){
                        this.cityList = res.result.organizeOrgList
                        if(this.cityList.length == 1){
                            this.cityId = this.cityList[0].id
                            this.grade = 2
                            this.code = this.cityList[0].code
                            this.getWarehouseList()
                        }
                    }
                })
            },
            // 选择城市
            cityChange(value){
                this.cityId = value
                this.grade = 2
                for(var item of this.cityList){
                    if(item.id == this.cityId){
                        this.code = item.code
                    }
                }
                this.organizeId = ''
                this.warehouseList = []
                this.getWarehouseList()
            },
            // 获取仓库
            getWarehouseList(){
                let params = {
                    cityIds: this.cityId
                }
                getWarehouse(params).then((res)=>{
                    if(res.success){
                        this.warehouseList = res.result.organizeOrgList
                        if(this.warehouseList.length == 1){
                            this.organizeId = this.warehouseList[0].id
                            this.grade = 3
                            this.code = this.warehouseList[0].code
                            this.onSearch()
                        }
                    }
                })
            },
            // 选择仓库
            warehouseChange(value){
                console.log(value)
                this.organizeId = value
                this.grade = 3
                for(var item of this.warehouseList) {
                    if(item.id == this.organizeId) {
                        this.code = item.code
                    }
                }
            },
            // 搜索
            onSearch() {
                if(this.dsCode){
                    if(this.roleGrade == 0){
                        this.getDSDetails()
                    }
                    if(this.roleGrade == 1){
                        if(this.regionId){
                            this.getDSDetails()
                        }else{
                            this.$message.warning('当前用户等级为大区等级，请选择大区！', 6)
                        }
                    }
                    if(this.roleGrade == 2){
                        if(this.cityId){
                            this.getDSDetails()
                        }else{
                            this.$message.warning('当前用户等级为城市等级，请选择大区和城市！', 6)
                        }
                    }
                    if(this.roleGrade == 3){
                        if(this.organizeId){
                            this.getDSDetails()
                        }else{
                            this.$message.warning('当前用户等级为仓库等级，请选择大区、城市和仓库！', 6)
                        }
                    }
                }else{
                    this.$message.warning('没有数据源编码，请从数据源页面进入本页面！', 6)
                }
            },
            // 重置
            onReset() {
                this.code = this.headquartersCode
                this.grade = this.roleGrade
                this.regionId = ''
                this.cityId = ''
                this.organizeId = ''
                this.cityList = []
                this.warehouseList = []
                this.data = []
                this.columns = []
                this.total = 0
                this.pageNo = 1
                this.pageSize = 10

                // 数据源详情默认取今天的数据
                var d = new Date()
                var curDateTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
                this.createTime_begin = curDateTime + ' ' + '00:00:00'
                this.createTime_end = curDateTime + ' ' + '23:59:59'
            },
            // 返回
            onBack() {
                this.$router.push({path: '/datacenter/datasource', query: {categoryName: this.categoryName, dataName: this.dataName, dataCode: this.dataCode,}});
            },
            getDSDetails() {
                let params = {
                    dsCode: this.dsCode,
                    grade: this.grade,
                    code: this.code,
                    createTime_begin: this.createTime_begin,
                    createTime_end: this.createTime_end,
                    pageSize: this.pageSize,
                    pageNo: this.pageNo,
                }
                this.tableLoading = true
                getDSDetails(params).then((res)=>{
                    this.tableLoading = false
                    if(res.success){
                        if(res.result.dsDetailTitleMap){
                            let arr = []
                            for(let i in res.result.dsDetailTitleMap){
                                arr.push({title: res.result.dsDetailTitleMap[i], key: i, dataIndex: i, align: 'center', })
                            }
                            this.columns = arr.filter(v => v.title != '' & v.title != '主键ID' & v.title != '主键')
                        }
                        // if(res.result.dsDetailList && res.result.dsDetailList.length > 0){
                            this.$nextTick(()=>{
                                this.total = res.result.dsDetailTotal
                                this.data = res.result.dsDetailList
                            })
                        // }
                    }
                })
            },
            // 获取当前页数、条数
            pageChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.onSearch()
            },
            // 获取当前页数、条数
            sizeChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.onSearch()
            },
            // 开始时间
            startChange(value, dateString) {
                this.createTime_begin = dateString
            },
            startOk(value) {
                console.log('onOk: ', value);
            },
            // 结束时间
            endChange(value, dateString) {
                this.createTime_end = dateString
            },
            endOk(value) {
                console.log('onOk: ', value);
            },
        },
        
    }
</script>

<style lang="less" scoped>
    .dataDetails{
        width: 100%;
        padding: 0 10px 10px 10px;
        font-style: Microsoft YaHei;
        background: #ffffff;
        box-sizing: border-box;
        .top_operation{
            margin-bottom: 10px;
            overflow: hidden;
            .every_operation{
                float: left;
                margin-top: 10px;
                margin-right: 20px;
                span{
                    display: inline-block;
                    width: 85px;
                }
            }
            .button_div{
                float: left;
                margin-top: 10px;
            }
        }
        .select_number{
            width: 100%;
            height: 36px;
            padding-left: 20px;
            margin-bottom: 10px;
            box-sizing: border-box;
            background: rgba(57, 72, 103, .22);
            line-height: 36px;
            .number_span{
                color: #ffffff;
                margin-right: 30px;
                b{
                    color: #394867;
                    margin: 0 15px;
                }
            }
            .clear_span{
                cursor: pointer;
                color: #394867;
            }
        }
        .data_source_list{
            h3{
                font-weight: bolder;
                margin-bottom: 10px;
            }
            .data_pagination{
                width: 100%;
                height: 32px;
                margin: 20px 0 10px 0;
            }
        }
    }
</style>